package tk.xboot.boot.conf;

import io.undertow.Undertow;
import io.undertow.UndertowOptions;
import io.undertow.servlet.api.SecurityConstraint;
import io.undertow.servlet.api.SecurityInfo;
import io.undertow.servlet.api.TransportGuaranteeType;
import io.undertow.servlet.api.WebResourceCollection;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.undertow.UndertowBuilderCustomizer;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;

//@Configuration
//@ConditionalOnWebApplication
public class H2Conf {

    /**
     * http service port
     */
    @Value("${server.http.port}")
    private Integer httpPort;

    /**
     * https service port
     */
    @Value("${server.port}")
    private Integer httpsPort;


    //@Bean
    public UndertowServletWebServerFactory embeddedServletContainerFactory() {
        final UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory();
        factory.addBuilderCustomizers(new UndertowBuilderCustomizer() {
            @Override
            public void customize(final Undertow.Builder builder) {
                builder.addHttpListener(httpPort, "0.0.0.0");
                builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true);
            }
        });

        factory.addDeploymentInfoCustomizers(deploymentInfo -> {
            // 开启HTTP自动跳转至HTTPS
            deploymentInfo.addSecurityConstraint(new SecurityConstraint()
                    .addWebResourceCollection(new WebResourceCollection().addUrlPattern("/*"))
                    .setTransportGuaranteeType(TransportGuaranteeType.CONFIDENTIAL)
                    .setEmptyRoleSemantic(SecurityInfo.EmptyRoleSemantic.PERMIT))
                    .setConfidentialPortManager(exchange -> httpsPort);
        });
        return factory;
    }
}
